//
//  WHNetworkUtil.swift
//  ttjx
//
//  Created by 文 on 2019/10/11.
//  Copyright © 2019 ttjx. All rights reserved.
//

import UIKit
import CommonCrypto
import Alamofire
import MCToast

class WHNetworkUtil: SessionManager {

    static var instance : WHNetworkUtil? = nil

    class func shareManager() -> WHNetworkUtil{
    
//        var header : HTTPHeaders = Alamofire.SessionManager.defaultHTTPHeaders
//        header["Authorization"] = ""
//        header.updateValue("application/json", forKey: "Accept")
//        header.updateValue("application/x-www-form-urlencoded", forKey: "Content-Type")
        
//        let header : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
        
        let configration = URLSessionConfiguration.default
//        configration.httpAdditionalHeaders = header
        configration.timeoutIntervalForRequest = 10
        
        let manager = SessionManager.default
        manager.delegate.sessionDidReceiveChallenge = {
            session,challenge in
            return    (URLSession.AuthChallengeDisposition.useCredential,URLCredential(trust:challenge.protectionSpace.serverTrust!))
        }

        instance = WHNetworkUtil(configuration: configration)

        return instance!
    }
    
    func GET(urlString : String,vc:UIViewController? = nil,authori:String? = nil,success : @escaping (_ responseObject : [String : AnyObject]) -> ()) -> () {
        var header : HTTPHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        if authori == nil{
            let auth = UserDefaults.standard.string(forKey: Authorization)
            header["Authorization"] = "\(auth ?? "")"
        }else{
            header["Authorization"] = "\(authori ?? "")"
        }
        
        Alamofire.request(urlString, method: .get, encoding: JSONEncoding.default,headers: header).responseJSON { (response) in
            DLLog(message: "\(response)")
            MCToast.mc_remove()
            switch response.result{
            case .success:
                
                if let value = response.result.value as? [String : AnyObject]{
                    DLLog(message: "\(urlString)  \(value)")
                    success(value)
                }else{
                    if (vc != nil){
                        let alertVc = UIAlertController(title: "异常的数据结构", message: "", preferredStyle: .alert)
                        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler:nil)
                        alertVc.addAction(cancelAction)

                        vc!.present(alertVc, animated:true, completion:nil)
                    }
                }
                break
            case .failure:
                DLLog(message: "网络请求错误：\(response)")
                break
            }
        }
    }

    /**
     urlString   接口
     parameters   参数
     isIOSCheckRequest  是否为审核版本接口
     isNeedToast  是否需要弹框
     vc   视图控制器
     success  成功回调
     */
    func POST(urlString : String, parameters : [String : AnyObject]?,isIOSCheckRequest:Bool? = false,isNeedToast:Bool? = false, vc:UIViewController? = nil,success : @escaping (_ responseObject : [String : AnyObject]) -> ()) -> () {
        DLLog(message: "请求接口：\(urlString) -- \(Date().todaySeconds)")
        DLLog(message: "请求报文：\(String(describing: parameters))")
        var header : HTTPHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        let auth = UserDefaults.standard.string(forKey: Authorization)
        header["Authorization"] = "\(auth ?? "")"
        Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default,headers: header).responseJSON { (response) in
            MCToast.mc_remove()
            DLLog(message: "\(urlString) response: \(response)")
            switch response.result{
            case .success:
                if let value = response.result.value as? [String : AnyObject]{
//                    DLLog(message: "\(urlString)  \(value)")
                    let code = value["code"]as? Int ?? -1
                    
                    if (code == 200 || urlString == URL_judge_ver) {
                        success(value)
                    }else if (urlString == URL_authen_user_cert && code == 402){
                        success(value)
                    }else if (urlString == URL_register && (code == 402 || code == 202)){
                        success(value)
                    }else{
                        if isNeedToast! && (vc != nil){
                            let alertVc = UIAlertController(title: "\(value["message"] as? String ?? "")", message: "\(value["msg"] as? String ?? "")", preferredStyle: .alert)
                            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler:nil)
                            alertVc.addAction(cancelAction)

                            vc!.present(alertVc, animated:true, completion:nil)
                        }
                    }
                }else{
                    if isNeedToast! && (vc != nil){
                        let alertVc = UIAlertController(title: "异常的数据结构", message: "", preferredStyle: .alert)
                        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler:nil)
                        alertVc.addAction(cancelAction)

                        vc!.present(alertVc, animated:true, completion:nil)
                    }
                }
                break
            case .failure:
                DLLog(message: "网络请求错误：\(response)") 
                break
            }
        }
    }

    public func md5(strs:String) ->String!{
       let str = strs.cString(using: String.Encoding.utf8)
       let strLen = CUnsignedInt(strs.lengthOfBytes(using: String.Encoding.utf8))
       let digestLen = Int(CC_MD5_DIGEST_LENGTH)
       let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
       CC_MD5(str!, strLen, result)
       let hash = NSMutableString()
       for i in 0 ..< digestLen {
           hash.appendFormat("%02x", result[i])
       }
       free(result)
        let signStr = String(format: hash as String)
        return signStr.uppercased()
    }
      
}

extension WHNetworkUtil{
    //    字典转换为JSONString
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    func getStrForSign(param:[String:String]) -> String{
        let paramTemp = Array(param.keys).sorted(by: <)
        
        var paramStr = ""
        for (_,item) in paramTemp.enumerated(){
            let keyStr = item
            let valueStr = param[item]
            let strTemp = keyStr + "=" + valueStr!
            paramStr = paramStr + strTemp + "&"
        }
        paramStr = paramStr + "key=A7FA6348FEBDCA8A64FDA192CA4812E6"
        DLLog(message: "paramStr :  \(paramStr)")
        
        return paramStr
    }
}

